package com.demo.vueservice.web.controller;

import com.demo.vueservice.common.entity.User;
import com.demo.vueservice.common.util.ResultGen;
import com.demo.vueservice.common.util.ResultObj;
import com.demo.vueservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/user")
public class UserController {

    private ResultGen resultGen;
    private UserService userService;

    @Autowired
    public UserController(UserService userService,ResultGen resultGen) {
        this.userService = userService;
        this.resultGen = resultGen;
    }


    // 注册用户
    @PostMapping("/register")
    public ResultObj saveUser(@Valid User user, BindingResult bindingResult){
        return resultGen.getSuccessResult("注册成功",userService.saveUser(user));
    }

    // 登录
    @PostMapping("/login")
    public ResultObj login(@NotNull(message = "用户名不能为空") String name, @NotNull(message = "密码不能为空") String pwd, HttpSession session){
       User user = userService.checkLogin(name,pwd);
        if(user!=null){
            // 存在session中
            session.setAttribute("user",user);
            return resultGen.getSuccessResult("登陆成功",user);
        }
        return resultGen.getFailResult("用户名/密码错误");
    }

    // 获取全部用户信息
    @GetMapping("/getUsers")
    public ResultObj getUsers(){
        return resultGen.getSuccessResult(userService.findUsers());
    }

    /**
     * 参数验证异常处理
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultObj handleConstraintViolationException(ConstraintViolationException cve){
        String errMsg = cve.getConstraintViolations().iterator().next().getMessage();
        return resultGen.getFailResult(errMsg);
    }

    /**
     * 主键唯一约束，异常捕获处理
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResultObj handleDataIntegrityViolationException(DataIntegrityViolationException dive){
        // 如果存在两个用户名相同，则会报这个错误
        return resultGen.getFailResult("违反主键/唯一约束异常");
    }

}
